package com.lianjia.sh.tools.util;

import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailUtil
{
    private static JavaMailSenderImpl senderImpl = null;
    private static boolean isDefault = true;
    private static String host = "smtp.163.com";
    private static String userName = "flypigs1@163.com";
    private static String password = "oiazneqlvdywfrqu";
    private static Long timeout = Long.valueOf(2000L);

    public static JavaMailSenderImpl instanceSingleton(String host, String userName, String password, Long timeout)
    {
        if (senderImpl != null) {
            return senderImpl;
        }
        if (StringUtils.isBlank(host)) {
            host = "smtp.qq.com";
        }
        if (timeout == null) {
            timeout = Long.valueOf(5000L);
        }
        senderImpl = new JavaMailSenderImpl();
        senderImpl.setHost(host);
        senderImpl.setUsername(userName);
        senderImpl.setPassword(password);
        Properties prop = new Properties();
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.timeout", timeout.toString());
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.put("mail.smtp.socketFactory.fallback", "false");

        senderImpl.setJavaMailProperties(prop);
        return senderImpl;
    }

    public static void sendMail(String subject, String content, String... toMail)
            throws MessagingException
    {
        //password = "78963214";
        if (isDefault) {
            instanceSingleton(host, userName, password, timeout);
        }

        MimeMessage mimeMessage = senderImpl.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        messageHelper.setSubject(subject);
        messageHelper.setFrom(senderImpl.getUsername());
        messageHelper.setTo(toMail);
        messageHelper.setText(content, true);
        senderImpl.send(mimeMessage);
    }

    public static void main(String args[]) throws MessagingException {
        sendMail("我是主题","这是 我发的内容","yangsp1@126.com");
    }
}
